from peewee import Model, CharField, BigAutoField, DateTimeField, TextField
from .db import mysql_db


class ChatMessage(Model):
    id = BigAutoField(primary_key=True)
    tid = CharField(max_length=60)
    type = CharField(max_length=10)
    content = TextField(null=False)
    created_at = DateTimeField(formats="%Y-%m-%d %H:%M:%S.%f")

    class Meta:
        database = mysql_db
        table_name = "chat_messages"


def append_chat_message(tid: str, type: str, content: str):
    ChatMessage(tid=tid, type=type, content=content).save()


def get_latest_messages(
    tid: str, n: int | None = None, type: str | None = None
) -> list[ChatMessage]:
    where = ChatMessage.tid == tid
    if type:
        where = where & (ChatMessage.type == type)

    query = (
        ChatMessage.select()
        .where(where)
        .order_by(ChatMessage.id.desc())
        .limit(10 if n is None or n < 1 else n)
    )
    return [it for it in query]
